from flask.globals import _request_ctx_stack
from flask_appbuilder import ModelView
from flask_appbuilder.fieldwidgets import Select2Widget
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.widgets import RenderTemplateWidget

from app.models import SerialPortCategory, SerialPort, CheckUnit, Profile, Post
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from app import appbuilder, db
import datetime


def query_serial_for_black():
    cat = db.session.query(SerialPortCategory).filter(SerialPortCategory.name == 'black').first()
    query = db.session.query(SerialPort)
    if cat:
        query = query.filter(SerialPort.category_id == cat.id)
    return query


def query_profile():
    return db.session.query(Profile)


class PostAddWidget(RenderTemplateWidget):
    """
        FormWidget

        form = None
        include_cols = []
        exclude_cols = []
        fieldsets = []
    """
    template = 'Post/form.html'


class PostShowWidget(RenderTemplateWidget):
    """
        FormWidget

        form = None
        include_cols = []
        exclude_cols = []
        fieldsets = []
    """
    template = 'Post/show.html'

    def __call__(self, **kwargs):
        ctx = _request_ctx_stack.top
        jinja_env = ctx.app.jinja_env

        template = jinja_env.get_template(self.template)
        args = self.template_args.copy()
        args.update(kwargs)
        include_columns = args.get('include_columns')
        label_columns = args.get('label_columns')
        value_columns = args.get('value_columns')
        for i in range(len(include_columns)):
            col = include_columns[i]
            label = label_columns.get(col)
            label = col if  label is None else label
            args[col] = dict(label=label, value=value_columns[i])
        return template.render(args)



class PostView(ModelView):
    datamodel = SQLAInterface(Post)

    list_columns = ['author', 'title', 'summary', 'created', 'modified']
    # edit_form_extra_fields = {'black': QuerySelectField('Black',
    #                                                     query_factory=query_serial_for_black,
    #                                                     widget=Select2Widget()),
    #                           'profile': QuerySelectField('Profile',
    #                                                       query_factory=query_profile,
    #                                                       widget=Select2Widget())
    #                           }
    # add_form_extra_fields = {'black': QuerySelectField('Black',
    #                                                     query_factory=query_serial_for_black,
    #                                                     widget=Select2Widget()),
    #                           'profile': QuerySelectField('Profile',
    #                                                       query_factory=query_profile,
    #                                                       widget=Select2Widget())
    #                           }

    add_widget = PostAddWidget
    edit_widget = PostAddWidget
    show_widget = PostShowWidget

    # show_template = 'CheckUnit/show_cascade.html'
    add_template = 'Post/add.html'
    edit_template = 'Post/edit.html'
    show_template = 'Post/detail.html'

    def _fill_form_exclude_cols(self, exclude_cols, form):
        """
            fill the form with the suppressed cols, generated from exclude_cols
        """
        from flask_login import current_user

        lst = form.author._get_object_list()
        for id,obj in lst:
            if id == str(current_user.id):
                form.author.data = current_user
                break
        form.created.data = datetime.datetime.now()
        form.created.raw_data = [str(form.created.data)]
        form.modified.data = datetime.datetime.now()
        form.modified.raw_data = [str(form.modified.data)]

        for filter_key in exclude_cols:
            filter_value = self._filters.get_filter_value(filter_key)
            rel_obj = self.datamodel.get_related_obj(filter_key, filter_value)
            if hasattr(form, filter_key):
                field = getattr(form, filter_key)
                field.data = rel_obj


# class SerialCategoryView(ModelView):
#     datamodel = SQLAInterface(SerialPortCategory)
#     related_views = [PostView]


appbuilder.add_view(PostView, "Posts", icon="fa-folder-open-o", category="Company")
# appbuilder.add_separator("Company")
# appbuilder.add_view(SerialCategoryView, "Departments", icon="fa-folder-open-o", category="Company")
